package com.kefu.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kefu.dto.MessageDTO;
import com.kefu.entity.Message;
import com.kefu.entity.Session;
import com.kefu.handler.ChatHandler;
import com.kefu.repository.MessageRepository;
import com.kefu.repository.SessionRepository;
import com.kefu.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import java.util.Map;

@Service
public class ChatServiceImpl implements ChatService {

    @Override
    public void handleUserOnline(String userId, String role) {
        System.out.println("用户[" + userId + "]上线，角色：" + role);
        if ("admin".equals(role)) {
            updateAdminStatus(userId, 1); // 1表示在线
        }
    }

    @Override
    public void handleUserOffline(String userId, String role) {
        System.out.println("用户[" + userId + "]下线，角色：" + role);
        if ("admin".equals(role)) {
            updateAdminStatus(userId, 0); // 0表示离线
        }
    }

    @Override
    public void handleMessage(String sessionId, String senderId, String receiverId, String content, String role) {
        int senderType = "admin".equals(role) ? 2 : 1;
        Message message = saveMessage(sessionId, senderId, senderType, content, 1);
        saveAndForwardMessage(message);
    }

    @Override
    public Message saveMessage(String sessionId, String senderId, int senderType, String content, int messageType) {
        Message message = new Message();
        message.setSessionId(sessionId);
        message.setSenderId(senderId);
        message.setSenderType(senderType);
        message.setContent(content);
        message.setMessageType(messageType);
        return message;
    }

    @Override
    public void updateAdminStatus(String adminId, int status) {
        System.out.println("客服[" + adminId + "]状态更新为：" + status);
    }

    @Override
    public void saveAndForwardMessage(Message message) {
        try {
            // 1. 保存消息到数据库
            message.setId(UUID.randomUUID().toString().replace("-", ""));
            message.setReadStatus(0); // 默认为未读
            message.setSendTime(new Date());
            messageRepository.save(message);

            System.out.println("保存消息成功：" + message.getId());

            // 2. 查找目标用户的WebSocket会话
            String sessionId = message.getSessionId();
            Session session = sessionRepository.findById(sessionId)
                    .orElseThrow(() -> new RuntimeException("会话不存在：" + sessionId));

            // 3. 确定消息接收者（用户/客服）
            String targetId;
            String targetRole;
            if (message.getSenderType() == 1) { // 发送者是用户，接收者是客服
                targetId = session.getAdminId();
                targetRole = "admin";
            } else { // 发送者是客服，接收者是用户
                targetId = session.getUserId();
                targetRole = "user";
            }

            // 4. 转换为DTO并转发消息（兼容Java 8的写法）
            if (targetId != null) {
                MessageDTO messageDTO = convertToDTO(message);

                // 使用HashMap创建Map（Java 8及以上通用）
                Map<String, Object> messageMap = new HashMap<>();
                messageMap.put("type", "message");
                messageMap.put("data", messageDTO);

                String jsonMessage = objectMapper.writeValueAsString(messageMap);

                // 使用ChatHandler发送消息
                chatHandler.sendMessage(targetId, targetRole, jsonMessage);
                System.out.println("转发消息给" + targetRole + "[" + targetId + "]：" + message.getContent());
            } else {
                System.out.println("消息转发失败：未找到接收者，会话ID：" + sessionId);
            }

        } catch (Exception e) {
            System.err.println("消息处理失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 需要添加的依赖注入
    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private SessionRepository sessionRepository;

    @Autowired
    private ChatHandler chatHandler;

    @Autowired
    private ObjectMapper objectMapper;

    // 转换工具方法
    private MessageDTO convertToDTO(Message message) {
        MessageDTO dto = new MessageDTO();
        dto.setId(message.getId());
        dto.setSessionId(message.getSessionId());
        dto.setSenderId(message.getSenderId());
        dto.setSenderType(message.getSenderType());
        dto.setContent(message.getContent());
        dto.setMessageType(message.getMessageType());
        dto.setReadStatus(message.getReadStatus());
        dto.setSendTime(message.getSendTime());
        return dto;
    }
}
